<template>
  <div class="image-test-container">
    <h2>图片显示测试页面</h2>
    
    <!-- 测试图片显示 -->
    <el-card class="test-card">
      <h3>图片显示测试</h3>
      
      <el-form :model="testForm" label-width="120px">
        <el-form-item label="图片URL">
          <el-input 
            v-model="testForm.imageUrl" 
            placeholder="请输入图片URL或路径"
            style="width: 400px"
          />
        </el-form-item>
        
        <el-form-item label="图片类型">
          <el-select v-model="testForm.imageType" placeholder="选择图片类型">
            <el-option label="网络图片" value="network" />
            <el-option label="本地文件路径" value="local" />
            <el-option label="Base64" value="base64" />
            <el-option label="Blob URL" value="blob" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <el-button type="primary" @click="testImageDisplay">测试显示</el-button>
    </el-card>
    
    <!-- 显示结果 -->
    <el-card class="test-card" v-if="testForm.imageUrl">
      <h3>显示结果</h3>
      
      <div class="image-display-area">
        <div class="image-info">
          <p><strong>URL:</strong> {{ testForm.imageUrl }}</p>
          <p><strong>类型:</strong> {{ testForm.imageType }}</p>
          <p><strong>是否有效:</strong> {{ isValidImageUrl(testForm.imageUrl) ? '是' : '否' }}</p>
          <p><strong>处理后的URL:</strong> {{ getImageUrl(testForm.imageUrl) }}</p>
        </div>
        
        <div class="image-preview">
          <h4>图片预览:</h4>
          <img 
            v-if="isValidImageUrl(testForm.imageUrl)" 
            :src="getImageUrl(testForm.imageUrl)" 
            class="preview-image"
            @error="handleImageError"
            @load="handleImageLoad"
            alt="测试图片"
          />
          <div v-else class="no-image">
            <el-icon><Picture /></el-icon>
            <span>无效的图片URL</span>
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 常见测试用例 -->
    <el-card class="test-card">
      <h3>常见测试用例</h3>
      
      <div class="test-cases">
        <el-button 
          v-for="testCase in testCases" 
          :key="testCase.name"
          @click="useTestCase(testCase)"
          size="small"
          style="margin: 5px"
        >
          {{ testCase.name }}
        </el-button>
      </div>
    </el-card>
    
    <!-- 文件上传测试 -->
    <el-card class="test-card">
      <h3>文件上传测试</h3>
      
      <el-upload
        class="upload-demo"
        action="#"
        :show-file-list="false"
        :before-upload="beforeUpload"
        :http-request="uploadFile"
      >
        <el-button type="primary">选择图片文件</el-button>
      </el-upload>
      
      <div v-if="uploadedImage" class="uploaded-image">
        <h4>上传的图片:</h4>
        <img :src="uploadedImage" class="preview-image" alt="上传的图片" />
        <p><strong>URL:</strong> {{ uploadedImage }}</p>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'

const testForm = reactive({
  imageUrl: '',
  imageType: 'network'
})

const uploadedImage = ref('')

// 测试用例
const testCases = [
  {
    name: '网络图片',
    url: 'https://via.placeholder.com/300x200/409eff/ffffff?text=Test+Image',
    type: 'network'
  },
  {
    name: 'Base64图片',
    url: '',
    type: 'base64'
  },
  {
    name: '相对路径',
    url: '/images/test.jpg',
    type: 'local'
  },
  {
    name: '绝对路径',
    url: 'C:/images/test.jpg',
    type: 'local'
  }
]

// 检查是否为有效的图片URL
const isValidImageUrl = (url: string): boolean => {
  if (!url) return false
  
  // 检查是否为blob URL（本地文件）
  if (url.startsWith('blob:')) return true
  
  // 检查是否为data URL（base64）
  if (url.startsWith('data:image/')) return true
  
  // 检查是否为http/https URL
  if (url.startsWith('http://') || url.startsWith('https://')) return true
  
  // 检查是否为相对路径（以/开头）
  if (url.startsWith('/')) return true
  
  // 检查是否为文件路径（包含常见图片扩展名）
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
  const lowerUrl = url.toLowerCase()
  return imageExtensions.some(ext => lowerUrl.includes(ext))
}

// 获取图片URL
const getImageUrl = (url: string): string => {
  if (!url) return ''
  
  // 如果是blob URL或data URL，直接返回
  if (url.startsWith('blob:') || url.startsWith('data:')) {
    return url
  }
  
  // 如果是相对路径，添加基础URL
  if (url.startsWith('/')) {
    return `${window.location.origin}${url}`
  }
  
  // 如果是完整URL，直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  
  // 如果是文件路径，尝试作为相对路径处理
  return url
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  console.warn('图片加载失败:', img.src)
  ElMessage.error('图片加载失败')
}

// 处理图片加载成功
const handleImageLoad = (event: Event) => {
  console.log('图片加载成功:', (event.target as HTMLImageElement).src)
  ElMessage.success('图片加载成功')
}

// 测试图片显示
const testImageDisplay = () => {
  if (!testForm.imageUrl) {
    ElMessage.warning('请输入图片URL')
    return
  }
  
  console.log('测试图片:', testForm.imageUrl)
  console.log('是否有效:', isValidImageUrl(testForm.imageUrl))
  console.log('处理后URL:', getImageUrl(testForm.imageUrl))
}

// 使用测试用例
const useTestCase = (testCase: any) => {
  testForm.imageUrl = testCase.url
  testForm.imageType = testCase.type
}

// 文件上传前检查
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 文件上传
const uploadFile = (options: any) => {
  const file = options.file
  const reader = new FileReader()
  
  reader.onload = (e) => {
    uploadedImage.value = e.target?.result as string
    ElMessage.success('图片上传成功')
  }
  
  reader.readAsDataURL(file)
}
</script>

<style scoped>
.image-test-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-card {
  margin-bottom: 20px;
}

.test-card h3 {
  margin-bottom: 16px;
  color: #303133;
}

.image-display-area {
  display: flex;
  gap: 20px;
  margin-top: 16px;
}

.image-info {
  flex: 1;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.image-info p {
  margin: 8px 0;
  word-break: break-all;
}

.image-preview {
  flex: 1;
  text-align: center;
}

.preview-image {
  max-width: 300px;
  max-height: 200px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  object-fit: contain;
}

.no-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  background: #fafafa;
  color: #909399;
}

.no-image .el-icon {
  font-size: 40px;
  margin-bottom: 8px;
  color: #c0c4cc;
}

.test-cases {
  margin-top: 16px;
}

.uploaded-image {
  margin-top: 16px;
  text-align: center;
}

.uploaded-image p {
  margin: 8px 0;
  word-break: break-all;
}
</style>



